import { ref, onMounted } from 'vue'

export function useBaiduMap({ elementId, centerPoint, initialZoom }) {
  const map = ref(null)

  const loadJScript = () => {
    return new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.type = 'text/javascript'
      script.src =
        '//api.map.baidu.com/api?type=webgl&v=1.0&ak=g2HTQYiHrmBY8zNOMaWeYlkwwcvhnD3m&callback=initMap'
      script.onerror = reject
      document.body.appendChild(script)
      window.initMap = () => {
        resolve()
      }
    })
  }

  const initMap = () => {
    map.value = new BMapGL.Map(elementId) // 创建Map实例
    map.value.centerAndZoom(
      new BMapGL.Point(centerPoint.lng, centerPoint.lat),
      initialZoom,
    )
    map.value.enableScrollWheelZoom(true) // 启用滚轮放大缩小
  }

  const setNewZoom = (zoom) => {
    if (map.value) {
      map.value.setZoom(zoom)
    }
  }

  const getMapZoom = () => {
    if (map.value) {
      return map.value.getZoom()
    }
    return null
  }

  onMounted(async () => {
    try {
      await loadJScript()
      initMap()
    } catch (error) {
      console.error('Failed to load Baidu Map script:', error)
    }
  })

  return {
    map,
    setNewZoom,
    getMapZoom,
  }
}
